// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
	
	const db = cloud.database()
	const _ =db.command
	const targetDB = db.collection(event.db)
	try {
		if(event.type == "insert"){
	    return await targetDB.add({
			  data: event.data
			})
		}
 
		else if(event.type == "update"){
	    return await targetDB.doc(event.indexKey).update({
	      data: event.data
	    })
		}
 
		else if(event.type == "delete"){
	    return await targetDB.where(event.condition).remove()
		}else if(event.type == "getpages"){
			console.log("get"+event.skip+"--"+event.limit)
			if(event.commandtype){
				
				for (let index = 0; index < event.commandtype.length; index++) {
					const element = event.commandtype[index];
					let ziduan = element.ziduan
					let t  = 	element.type
					let v = element.value
					if(t=='gt'){
				  	event.condition[ziduan] =_.gt(v)
				  }else 	if(t=='lt'){
						event.condition[ziduan] =_.lt(v)
					}
				}
			}
			const countResult = await db.collection(event.db).where(event.condition).count()
			const total = countResult.total
			console.log("get"+event.skip+"--"+event.limit)
			let datas	= await db.collection(event.db).where(event.condition).orderBy("dateAdd","desc").skip(event.skip).limit(event.limit).get()
	    return {
				total:total,
				result:datas
			}
		}else if(event.type == "count"){
	    return await targetDB.where(event.condition).count()
		 
		} else if(event.type == "getall"){
			      const _ =db.command
			      const MAX_LIMIT = 100
			    
			      if(event.commandtype){
			        
			        for (let index = 0; index < event.commandtype.length; index++) {
			          const element = event.commandtype[index];
			          let ziduan = element.ziduan
			          let t  =  element.type
			          let v = element.value
			          if(t=='gt'){
			            event.condition[ziduan] =_.gt(v)
			          }else   if(t=='lt'){
			            event.condition[ziduan] =_.lt(v)
			          }else   if(t=='in'){
				           console.log('in')
				            event.condition[ziduan] =_.in(v)
				          }
			        }
			      }
			      
			      console.log("getall----"+event)
			      // 先取出集合记录总数
			        const countResult = await targetDB.where(event.condition).count()
			        const total = countResult.total
			        // 计算需分几次取
			        const batchTimes = Math.ceil(total / 100)
			        // 承载所有读操作的 promise 的数组
			        const tasks = []
			        for (let i = 0; i < batchTimes; i++) {
			          const promise = targetDB.where(event.condition).orderBy("dateAdd","desc").skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
			          tasks.push(promise)
			        }
			        // 等待所有
			        return (await Promise.all(tasks)).reduce((acc, cur) => {
			          return {
			            data: acc.data.concat(cur.data),
			            errMsg: acc.errMsg,
			            total:cur.data.length
			          }
			        })
			    }
		
  } catch (e) {
    console.error(e)
  }
}